﻿using Colorful.Furniture.BasicDataManagement;
using Colorful.Furniture.ErpOrderManagement;
using Colorful.Furniture.Extensions;
using Colorful.Furniture.FinanceSdk;
using Colorful.Furniture.InterfaceDownstream;
using Colorful.Furniture.ResultManagement;
using Dop.Core;
using Essensoft.Paylink.Alipay.Domain;
using Flurl.Http;
using FreeSql;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.BackgroundJobs;
using Volo.Abp.DependencyInjection;

namespace Colorful.Furniture.BackgroundManagement;

/// <summary>
/// 推送拼多多店铺失败信息-后台作业
/// </summary>
public class SentNotifyPddJob : BackgroundJob<SentNotifyPddArgs>, ISingletonDependency
{
    private readonly IFreeSql _freeSql;
    private readonly ILogger<SentNotifyPddArgs> _logger;
    private readonly IBaseRepository<RechargeOrderCallbackLog> _customerOrderCallbackLogRepository;
    private readonly IBackgroundJobManager _backgroundJobManager;
    private readonly FileConfig _fileConfig;

    public SentNotifyPddJob(
        IBackgroundJobManager backgroundJobManager,
        IFreeSql freeSql,
        ILogger<SentNotifyPddArgs> logger,
        IBaseRepository<RechargeOrderCallbackLog> customerOrderCallbackLogRepository,
        IOptions<FileConfig> fileConfig
    )
    {
        _backgroundJobManager = backgroundJobManager;
        _freeSql = freeSql;
        _logger = logger;
        _customerOrderCallbackLogRepository = customerOrderCallbackLogRepository;
        _fileConfig = fileConfig.Value;
    }



    /// <summary>
    /// 执行推送订单信息
    /// </summary>
    /// <param name="args"></param>
    public override async void Execute(SentNotifyPddArgs args)
    {
        // 暂停0.8秒
        await Task.Delay(800); // 1000毫秒等于1秒

        //获取订单提交时间
        var timeNow = DateTime.Now;

        var signStr = new SortedList<string, object>
        {
            {"type", "pdd.virtual.mobile.charge.notify"},
            {"client_id", "f4df955e3d434db9af7d0911ddf5a225"},
            {"access_token", "088b708344ce49fc97cf40073e4a1440cf47e50d"},
            {"timestamp", DateTimeExtensions.DateTimeToTimeStamp(timeNow)},
            {"data_type", "JSON"},
            {"ele_invoice", 0},
            {"order_sn", args.OrderSn},
            {"outer_order_sn", args.OuterOrderSn},
            {"status", args.Status}
        };
        StringBuilder builderSign = new StringBuilder();
        foreach (KeyValuePair<string, object> item in signStr)
        {
            var name = item.Key;
            var value = item.Value == null ? "" : item.Value.ToString();
            if (value != "")
            {
                builderSign.Append(name + value);
            }
        }

        var clientSecret = "d940c213db14ee22a8a0a09e20150019e314ab33";
        var signTemp = $"{clientSecret}{builderSign}{clientSecret}";
        // 大写加密
        var sign = Md5Encrypt.Md5Encrypt32(signTemp);

        var postStr = new SortedList<string, object>
        {
            {"type", "pdd.virtual.mobile.charge.notify"},
            {"client_id", "f4df955e3d434db9af7d0911ddf5a225"},
            {"access_token", "088b708344ce49fc97cf40073e4a1440cf47e50d"},
            {"timestamp", DateTimeExtensions.DateTimeToTimeStamp(timeNow)},
            {"data_type", "JSON"},
            {"ele_invoice", 0},
            {"order_sn", args.OrderSn},
            {"outer_order_sn", args.OuterOrderSn},
            {"status", args.Status},
            {"sign", sign},
        };
        StringBuilder builder = new StringBuilder();
        foreach (KeyValuePair<string, object> item in postStr)
        {
            var name = item.Key;
            var value = item.Value == null ? "" : item.Value.ToString();
            if (value != "")
            {
                builder.Append(name + "=" + value + "&");
            }
        }
        var postUrl = "http://gw-api.pinduoduo.com/api/router";
        var postQuery = builder.ToString().TrimEnd('&');

        try
        {
            var postResult = await postUrl.PostUrlEncodedAsync(postQuery).ReceiveJson<SuccessResultPddOutputDto>();

            if (postResult.mobile_charge_notify_response != null) //回调成功
            {
                _logger.LogWarning($"结束执行拼多多回调，回调响应成功 - 订单编号：{args.OuterOrderSn}，{args.OrderSn}，" +
                                   $"回调结果：Status={postResult.mobile_charge_notify_response.success}");

            }
            else //回调失败
            {

                _logger.LogWarning($"【推送充值信息失败】-【拼多多店铺】 - 订单编号：{args.OuterOrderSn}，{args.OrderSn}，推送状态：{args.Status}，" +
                                   $"返回内容：sub_msg={postResult.error_response.sub_msg}，error_msg={postResult.error_response.error_msg}");
            }
        }
        catch (Exception e)
        {
            _logger.LogWarning($"【推送充值信息失败】-【拼多多店铺】 - 订单编号：{args.OuterOrderSn}，{args.OrderSn}，推送状态：{args.Status}，" +
                               $"失败原因：{e.Message}");
        }

    }



    /// <summary>
    /// JSON反序列化
    /// </summary>
    public static T JsonDeserialize<T>(string jsonString)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
    }

}

/// <summary>
/// 拼多多返回体
/// </summary>
public class SentNotifyPddArgs
{
    /// <summary>
    /// 虚拟系统充值结果，SUCCESS-充值成功，FAIL-充值失败
    /// </summary>
    public string Status { get; set; }

    /// <summary>
    /// 拼多多订单编码
    /// </summary>
    public string OrderSn { get; set; }

    /// <summary>
    /// 外部系统订单编码
    /// </summary>
    public string OuterOrderSn { get; set; }

}
